package com.putao.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import com.putao.constants.OAuthConstant;
import com.putao.domain.SysRole;
import com.putao.domain.SysUser;
import com.putao.feign.UserFeign;
import com.putao.model.SecurityUser;
import com.putao.result.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * UserDetailsService的实现类，从数据库加载用户的信息，比如密码、角色。。。。
 */
@Service
public class JwtTokenUserDetailsService implements UserDetailsService {

    @Autowired
    private UserFeign userFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        JsonResult userResult = userFeign.getByUsername(username);
        if (!userResult.isSuccess()) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        SysUser user = JSON.parseObject(JSON.toJSONString(userResult.getData()), SysUser.class);
        JsonResult<List<SysRole>> roleResult = userFeign.getRolesByRoleIds(user.getRoleIds());
        if (!roleResult.isSuccess()) {
            throw new UsernameNotFoundException("获取角色失败！");
        }
        List<SysRole> roleList = roleResult.getData();
        List<String> roles = roleList.stream().map(sysRole -> OAuthConstant.ROLE_PREFIX + sysRole.getCode()).collect(Collectors.toList());
        return SecurityUser.builder()
                .id(user.getId())
                .username(user.getUsername())
                .avatar(user.getAvatar())
                .phone(user.getPhone())
                .email(user.getEmail())
                .password(user.getPassword())
                //将角色放入authorities中
                .authorities(AuthorityUtils.createAuthorityList(ArrayUtil.toArray(roles,String.class)))
                .build();
    }
}
